package cn.wolfcode.trip.api.websocket;


import cn.wolfcode.trip.base.domain.Chat;
import cn.wolfcode.trip.base.domain.Personality;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.ChatMapper;
import cn.wolfcode.trip.base.mapper.PersonalityMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MyHandler extends TextWebSocketHandler {
    private static final Map<Long, WebSocketSession> users;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private PersonalityMapper personalityMapper;
    static {
        users = new HashMap<>();
    }

    /**
     * 连接成功时候，会触发页面上onopen方法
     */
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //连接成功存放到缓存中
        Long id = (Long) session.getAttributes().get("id");
        users.put(id, session);
        System.out.println("连接成功,当前数量:"+users.size());
        //users.put(id ,session);
        //这块会实现自己业务，比如，当用户登录后，会把离线消息推送给用户
        //TextMessage returnMessage = new TextMessage("你将收到的离线");
        //session.sendMessage(returnMessage);
    }

    /**
     * 关闭连接时触发
     */
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        Long id = (Long) session.getAttributes().get("id");
        System.out.println(id+ " 已退出！");
        users.remove(id);
        System.out.println("剩余在线用户:"+users.size());
    }

    /**
     * js调用websocket.send时候，会调用该方法
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        Chat chat = JSON.parseObject(payload, Chat.class);
        chat.setSendTime(new Date());
        String content = chat.getContent();

        //敏感词过滤
        List<Personality> personalities = personalityMapper.selectAll();//得到数据库中存储的敏感词集合
        for (Personality personality : personalities) {//遍历
            //判断评论当中是否包含集合中的某个敏感词
            if( content.contains(personality.getWord())){

                StringBuffer str = new StringBuffer();
                for (int i = 0; i < personality.getWord().length(); i++) {//是的话就得到当前敏感词的长度
                    str.append("*");//遍历，拼接与长度相同的*代替敏感词
                }
                chat.setContent(content.replace(personality.getWord(),str));
            }
        }

        chatMapper.insert(chat);
        //如果接收人在线,  通知接收人
        if (isOnline(chat.getReceiveUser().getId())) {
            User sendUser = userMapper.selectByPrimaryKey(chat.getSendUser().getId());
            chat.setSendUser(sendUser);
            WebSocketSession receiveSession = users.get(chat.getReceiveUser().getId());
            receiveSession.sendMessage(new TextMessage(JSON.toJSONString(chat)));
        }
    }

    /**
     * 判断用户是否在线
     * @param id
     */
    private boolean isOnline(Long id) {
        for (Map.Entry<Long, WebSocketSession> entry : users.entrySet()) {
            if(entry.getKey().equals(id)){
                return true;
            }
        }
        return false;
    }








    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {

        for (Map.Entry<Long, WebSocketSession> entry : users.entrySet()) {
            WebSocketSession wsSession = entry.getValue();
            if (wsSession.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) {
                try {
                    if (wsSession.isOpen()) {
                        wsSession.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (Map.Entry<Long, WebSocketSession> entry : users.entrySet()) {
            WebSocketSession session = entry.getValue();
            try {
                if (session.isOpen()) {
                    session.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}